// 数据库操作
const mongoose = require('mongoose');
// 对象规则验证
const Joi = require('joi');
// 模型规则类
const Schema = mongoose.Schema;

// 店铺规则对象
const storeModel = new Schema({
		// 店铺名称
		store_name: {
			type: String,
			minlength: 5,
			maxlength: 30,
			required: true,
		},
		// 店铺简介
		store_intro: {
			type: String,
			minlength: 50,
			maxlength: 300,
			required: true,
		},
		// 店铺宣传照
		store_banner: [{
			type: String,
			required: true,
		}],
		// 店铺商品
		store_goods: [{
			type: mongoose.Schema.Types.ObjectId,
			ref: 'Goods'
		}],
		// 店铺商品分类 三级分类
		store_cate: [{
			type: mongoose.Schema.Types.ObjectId,
			ref: 'CategoryThree'
		}],
		// 商家用户id
		store_belong: {
			type: mongoose.Schema.Types.ObjectId,
			ref: 'User'
		},
		// 店铺地址
		address: [{
			type: String,
			required: true,
			default: ''
		}],
		// 发件地址
		send_address: [{
			type: String,
			required:true,
			default: ''
		}],
		// 店铺联系电话
		phone: {
			type: String,
			required: true,
			minlength: 11,
			maxlength: 11
		},
		// 添加时间
		add_time: {
			type: Date,
			default: Date.now
		},
}, {versionKey: false});

// 创建商品集合 
const Store = mongoose.model('store',storeModel,'store');


// 商品分类格式校验
const validateStore = store => {
	// 定义对象验证规则
	const schema = {
		store_name: Joi.string().min(5).max(30).required().error(new Error('店铺名称不符合验证验证规则')),
		store_intro: Joi.string().min(50).max(300).required().error(new Error('店铺简介字数不符合验证规则')),
		store_banner: Joi.any().empty(),
		address: Joi.array().required().error(new Error('店铺地址不能为空')),
		phone: Joi.string().min(11).max(11).required().regex(/^1[3|4|5|7|8][0-9]{9}$/).error(new Error('联系电话格式不正确')),
		add_time: Joi.date().default(Date.now, 'created time')
	};
	// 验证
	return Joi.validate(store, schema, {
		// 检测到所有错误
		abortEarly: false,
		// 允许对象包含被忽略的未知键
		allowUnknown: true
	});
}



// 导出模块成员
module.exports = {
	Store,
	validateStore
}
